package com.yjd.api.user;

import com.yjd.comm.annotation.ServiceRemoteProxy;
import com.yjd.comm.app.model.PushRegidModel;
import com.yjd.comm.app.service.IPushRegidService;
import com.yjd.comm.bank.model.BankModel;
import com.yjd.comm.bank.service.IBankService;
import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.device.model.DeviceModel;
import com.yjd.comm.device.service.IDeviceService;
import com.yjd.comm.enums.DeviceStatus;
import com.yjd.comm.enums.GenderEnum;
import com.yjd.comm.user.dto.UserSession;
import com.yjd.comm.user.model.UserDataModel;
import com.yjd.comm.user.model.UserModel;
import com.yjd.comm.user.service.IUserDataService;
import com.yjd.comm.user.service.IUserService;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.util.StringUtil;
import com.yjd.comm.util.UserAccessTokenUtil;
import com.yjd.comm.vo.CachedKeys;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户登陆处理
 * Created by yangchangyan on 2017/6/27.
 */
@Controller("com.yjd.api.user.LoginControl")
@Scope("prototype")
public class LoginControl extends BaseControl {

    @Resource
    private IUserService userService;

    @Resource
    private IPushRegidService pushRegidService;

    @Resource
    private IDeviceService deviceService;

    @Resource
    private IUserDataService userDataService;

    @Resource
    private IBankService bankService;

    @RequestMapping(value = "/msgdemo")
    public void msgdemo()throws Exception{
        String id = request.getParameter("id");
        userService.MsgDemo(Long.parseLong(id));
    }

    /**
     * 登录，两种登陆方式：
     * 1、手机号登陆，使用密码验证
     * 2、登陆成功后，可使用access_token快捷登陆
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public void login(@RequestParam(required = false) String mobile_number,
                      @RequestParam(required = false) String password,
                      @RequestParam(required = false) String regid)
            throws Exception {

        // 参数校验
        if (StringUtils.isEmpty(mobile_number) || StringUtils.isEmpty(password)) {
            FrameUtil.throwBaseException1("参数不完整");
        }

        UserModel uModel = userService.login(mobile_number, password);

        if (uModel == null) {
            this.errorMsg("用户名或密码错误");
            return;
        }

        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        DeviceModel device = deviceService.getModelOne(FrameUtil.newHashMap(
                "user_id", uModel.getUser_id()), DbWREnums.READ);

        // 更新设备使用情况
        Long currentTime = FrameUtil.getTime();
        if (null == device) {
            device = new DeviceModel();
            device.setUser_id(uModel.getUser_id());
            device.setLast_login_time(currentTime);
            device.setCreate_time(currentTime);
            device.setLast_update_time(currentTime);
            device.setDevice_name((String) paramMap.get("device_name"));
            device.setDevice_no((String) paramMap.get("device_no"));
            device.setInuse(DeviceStatus.enable.getCode());
            deviceService.insert(device);
        } else {
            device.setLast_login_time(currentTime);
            device.setLast_update_time(currentTime);
            device.setDevice_name((String) paramMap.get("device_name"));
            device.setDevice_no((String) paramMap.get("device_no"));
            device.setInuse(DeviceStatus.enable.getCode());
            deviceService.update(device);
        }

        //记录极光推送id
        if (StringUtils.isNotEmpty(regid)) {
            PushRegidModel regidModel = pushRegidService.getModelOne(FrameUtil.newHashMap("user_id", uModel.getUser_id()), DbWREnums.READ);
            if (null == regidModel) {
                regidModel = new PushRegidModel();
                regidModel.setUser_id(uModel.getUser_id());
                regidModel.setRegid(regid);
                regidModel.setCreate_time(currentTime);
                pushRegidService.insert(regidModel);
            } else {
                regidModel.setRegid(regid);
                regidModel.setCreate_time(currentTime);
                pushRegidService.updateByMap(regidModel);
            }
        }

        UserSession session = userService.getUserSession(uModel.getUser_id());
        // 生成token
        String serverToken = UserAccessTokenUtil.generateAccessToken(session);

        String img_url = StringUtils.isEmpty(uModel.getPortrait_path()) ? "" : ServletUtil.getFileUrl(uModel.getPortrait_path());

        // 查询用户详细信息
        UserDataModel userDate = userDataService.getModelById(session.getUser_id(), DbWREnums.READ);
        if (null == userDate) {
            this.errorMsg("用户信息异常,请联系客服！");
            return;
        }

        this.request.setAttribute(CachedKeys.LOGIN_USER, session);

        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("portrait_path", userDate.getPortrait_path());
        userInfo.put("idname", session.getIdname());
        userInfo.put("idcard", session.getIdcard());
        userInfo.put("mobile_number", session.getMobile_number());
        userInfo.put("birthday", session.getBirthdayFormmater());
        userInfo.put("gender", GenderEnum.parse(session.getGender()).getLabel());
        userInfo.put("lastMobileLoginTime", session.getLastMobileLoginTime());
        userInfo.put("credit_line", userDate.getCredit_line());
        userInfo.put("residual_amount", userDate.getResidual_amount());
        userInfo.put("user_status", session.getUser_status()); // 用户状态，0：可用，1：冻结

        // 是否设置交易密码 0否 1是
        userInfo.put("isPayPassword", StringUtil.isEmpty(session.getPay_password()) ? 0 : 1);

        // 是否绑卡 0否 1是
        userInfo.put("isBindCard", "1");
        BankModel userBank = bankService.getModelById(userDate.getUser_id(), DbWREnums.READ);
        if (null == userBank) {
            userInfo.put("isBindCard", "0");
        }

        this.successData(FrameUtil.newHashMap(
                "access_token", serverToken,
                "userInfo", userInfo,
                "user_id", userDate.getUser_id()));
    }

    /**
     * 快捷登录
     *
     * @throws Exception void
     */
    @RequestMapping(value = "login/shortcut", method = RequestMethod.POST)
    public void shortcut(@RequestParam(required = false) Long user_id,
                         @RequestParam(required = false) String access_token)
            throws Exception {

        // 参数校验
        if (StringUtils.isBlank(access_token) || user_id == null) {
            FrameUtil.throwBaseException1("参数不完整");
        }

        // 验证token
        String serverToken = UserAccessTokenUtil.generateAccessToken(userService.getUserSession(user_id));
        if (!serverToken.equals(access_token)) {
            this.errorMsg("登录信息已过期,请重新登录");
            return;
        }

        // 查询用户详细信息
        UserSession userIfno = userService.getUserSession(user_id);
        if (userIfno == null) {
            this.errorMsg("非法参数");
            return;
        }

        this.successData(FrameUtil.newHashMap(
                "access_token", serverToken,
                "user_id", userIfno.getUser_id(),
                "userInfo", userIfno));
    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public void loginOut(@RequestParam(required = false) String user_id) throws Exception {
        if (StringUtils.isNotEmpty(user_id)) {
            PushRegidModel regidModel = pushRegidService.getModelOne(FrameUtil.newHashMap("user_id", user_id), DbWREnums.READ);
            if (null != regidModel) {
                pushRegidService.delete(regidModel.getId());
            }

            Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
            DeviceModel device = deviceService.getModelOne(FrameUtil.newHashMap(
                    "user_id", user_id,
                    "device_no", paramMap.get("device_no")), DbWREnums.READ);

            // 更新设备使用情况
            Long currentTime = FrameUtil.getTime();
            if (null != device) {
                device.setLast_login_time(currentTime);
                device.setLast_update_time(currentTime);
                device.setInuse(DeviceStatus.unable.getCode());
                deviceService.update(device);
            }
        }
        this.request.setAttribute(CachedKeys.LOGIN_USER, null);
        super.successMsg("退出登录成功");
    }
}
